<?php

class Zone_Module{

    private $cityid = 0;
    private $data   = array();
    private $index  = array();
    private $pinyin = array();

    function __construct($cityid){
        $this->cityid = intval($cityid);
        $this->initCache();
    }

    private function cacheName(){
        return 'system.zone.'.$this->cityid;
    }

    private function initCache(){
        $cache = Cache::get($this->cacheName());
        if($cache){
            $this->data   = $cache['data'];
            $this->index  = $cache['index'];
            $this->pinyin = $cache['pinyin'];
        }
    }

    // @return array<stdClass>
    function getZoneList($id){
        $data = array();
        if(isset($this->index[$id])){
            foreach($this->index[$id] as $zid){
                $data[$zid] = $this->getZoneById($zid);
            }
        }
        return $data;
    }

    // @return stdClass
    function getZoneById($id){
        if(isset($this->data[$id])){
            return $this->data[$id];
        }else{
            return null;
        }
    }

    // @return stdClass
    function getZoneByPy($py){
        if(isset($this->pinyin[$py])){
            return $this->getZoneById($this->pinyin[$py]);
        }else{
            return null;
        }
    }

    function hasZone($id){
        return isset($this->index[$id]);
    }

    function makeCache(){
        require SYSTEM_DIR.'function/iconv.func.php';

        $zones = DB::getAll("SELECT zone_id, parent_id, name, pinyin, zone_type, display FROM `biz_zone`
                            WHERE `city_id` = '{$this->cityid}' ORDER BY `ordnum`");

        $pinyin = $index = $data = array();
        foreach($zones as $z){
            if(!$z['pinyin']){
                $_name = iconv(CHARSET, 'GBK', $z['name']);
                $z['pinyin'] = join('', gbk_to_pinyin($_name));
            }
            $t = 0;
            while(array_key_exists($z['pinyin'], $pinyin)){
                $t++;
                $z['pinyin'] = $z['pinyin'].$t;
            }
            $pinyin[$z['pinyin']] = $z['zone_id'];
            $index[$z['parent_id']][] = $z['zone_id'];
            $data[$z['zone_id']] = (Object) $z;
        }
        $cache = array(
            'pinyin' => $pinyin,
            'index'  => $index,
            'data'   => $data,
        );

        Cache::set($this->cacheName(), $cache);
    }

    function getData(){
        return $this->data;
    }
}
?>